package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.dao.mapper.DepartmentExtMapper;
import com.attendance.www.hr.dao.mapper.RoleDepartmentExtMapper;
import com.attendance.www.hr.dao.mapper.RoleDepartmentMapper;
import com.attendance.www.hr.dao.mapper.RoleExtMapper;
import com.attendance.www.hr.dao.mapper.RoleMapper;
import com.attendance.www.hr.entitys.Department;
import com.attendance.www.hr.entitys.Role;
import com.attendance.www.hr.entitys.RoleDepartment;
import com.attendance.www.hr.entitys.RoleDepartmentExample;
import com.attendance.www.hr.entitys.RoleExample;
import com.attendance.www.hr.enums.RoleEnum;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IRoleExcelService;

@Service
public class RoleExcelServiceImpl implements IRoleExcelService {

	@Resource
	private RoleMapper roleDao;
	@Resource
	private RoleExtMapper roleExtDao;
	@Resource 
	private DepartmentExtMapper departmentExtDao;
	@Resource 
	private RoleDepartmentExtMapper roleDepartmentExtDao;
	@Resource 
	private RoleDepartmentMapper roleDepartmentDao;

	private Map<String, Integer> addRoleMap;

	private Map<String, Integer> originalRoleMap;

	private Map<String, Role> roleMap;
	
	private Map<String, Department> departmentMap;

	/**
	 * 删除岗位相关数据
	 * 
	 * @return
	 */
	@Override
	public boolean delRole() {
		return true;
	}

	@Override
	public List<String> importRole(Workbook work, AttachmentBean attachmentBean) {
		Calendar calendar = Calendar.getInstance(); //得到日历
		calendar.setTime(attachmentBean.getFromDate());//把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
		Date ThruDate = calendar.getTime();   //得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType()==3){
			RoleExample example = new RoleExample();
			RoleExample.Criteria criteria=example.createCriteria();
			criteria.andThruDateIsNull();
			Role role =new Role();
			role.setThruDate(ThruDate);
			
			roleDao.updateByExampleSelective(role, example);
			RoleDepartmentExample roleDepartmentExample = new RoleDepartmentExample();
			RoleDepartmentExample.Criteria roleDepartmentCriteria=roleDepartmentExample.createCriteria();
			roleDepartmentCriteria.andThruDateIsNull();
			RoleDepartment roleDepartment =new RoleDepartment();
			roleDepartment.setThruDate(ThruDate);
			roleDepartmentDao.updateByExampleSelective(roleDepartment, roleDepartmentExample);
		}
		
		addRoleMap = new HashMap<String, Integer>();

		roleMap = new HashMap<String, Role>();

		originalRoleMap = new HashMap<String, Integer>();
		
		departmentMap= new HashMap<String ,Department>();

		List<String> successList = new ArrayList<String>();

		// 判断导入类型 1.覆盖 2.增量
		if (!(attachmentBean.getType()==3)) {
			List<Role> rolesList = roleExtDao.getRoleListByExcel(attachmentBean);
			for (Role role : rolesList) {
				roleMap.put(role.getRoleCode(), role);
				addRoleMap.put(role.getRoleCode(), -1);
				oldThruDate = role.getThruDate();
			}
		}
		List<Department> departmentList=departmentExtDao.getDepartmentListByExcel(attachmentBean);
		for (Department department : departmentList) {
			departmentMap.put(department.getDepartmentCode(), department);
		}

		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.3岗位")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Role role = new Role();// 创建岗位对象
					RoleDepartment roleDepartment =new RoleDepartment();
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							role.setThruDate(oldThruDate);
							
							roleDepartment.setThruDate(oldThruDate);
						}
					}
					role.setFromDate(attachmentBean.getFromDate());
					roleDepartment.setFromDate(attachmentBean.getFromDate());
					if (attachmentBean.getType()==1)
						if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
							String roleCode = row.getCell(0).toString();
							if (originalRoleMap.containsKey(roleCode)) {
								if (originalRoleMap.get(roleCode).intValue() > 0) {
									str.append("与第" + originalRoleMap.get(roleCode) + "行原岗位编码(" + roleCode + ")重复,");
								} else {
									str.append("原岗位编码(" + roleCode + ")已存在,");
								}
							} else {
								if (roleMap.containsKey(roleCode)) {
									role.setRoleId(roleMap.get(roleCode).getRoleId());
									role.setIsDisabled(roleMap.get(roleCode).getIsDisabled());
									originalRoleMap.put(row.getCell(0).toString(), i + 1);
									roleDepartment.setRoleId(roleMap.get(roleCode).getRoleId());
									role.setFromDate(roleMap.get(roleCode).getFromDate());
									roleDepartment.setFromDate(roleMap.get(roleCode).getFromDate());
								} else {
									str.append("原岗位编码不存在,");
								}
							}
						} else {
							str.append("原岗位编码不能为空,");
						}
					// 判断第一列上级岗位编码
					if (row.getCell(1) != null && StringUtils.isNotBlank(row.getCell(1).toString())) {
						String roleCode = row.getCell(1).toString();
						// 根据岗位编码查找在数据库中是否存在
						if (addRoleMap.containsKey(roleCode)) {
							role.setParentId(roleMap.get(roleCode).getRoleId());
						} else {
							str.append("上级岗位编码(" + roleCode + ")不存在,");
						}
					}

					if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
						String roleCode = row.getCell(3).toString();
						role.setRoleCode(roleCode);
						if (attachmentBean.getType()==1 && row.getCell(0) != null
								&& StringUtils.isNotBlank(row.getCell(0).toString())) {
							String oldRoleCode = row.getCell(0).toString();
							if (addRoleMap.containsKey(roleCode) && !oldRoleCode.equals(roleCode)) {
								if (addRoleMap.get(roleCode) > 0) {
									str.append("与第" + addRoleMap.get(roleCode) + "行岗位编码(" + roleCode + ")重复,");
								} else {
									str.append("岗位编码(" + roleCode + ")已存在,");
								}
							}
						} else {
							if (addRoleMap.containsKey(roleCode)) {
								if (addRoleMap.get(roleCode) > 0) {
									str.append("与第" + addRoleMap.get(roleCode) + "行岗位编码(" + roleCode + ")重复,");
								} else {
									str.append("岗位编码(" + roleCode + ")已存在,");
								}
							} 
						}
					} else {
						str.append("现岗位编码不能为空,");
					}

					// 判断第二列岗位名称的合法性
					if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
						role.setRoleName(row.getCell(4).toString());
					} else {
						str.append("岗位名称不能为空,");
					}

					// 判断第三列组织架构级别
					if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
						try {
							Integer orgLevel = RoleEnum.getName(row.getCell(5).toString());
							role.setRoleLevel(orgLevel);
						}catch (Exception e) {
							str.append("岗位级别格式不正确,");
						}
					}

					// 第四列描述
					if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
						String departmentNo = row.getCell(6).toString();
						if(departmentMap.containsKey(departmentNo)) {
							roleDepartment.setDepartmentId(departmentMap.get(departmentNo).getDepartmentId());
						}else {
							str.append("所属部门不存在,");
						}
					}else {
						str.append("所属部门不能为空,");
					}
					// 第四列描述
					if (row.getCell(8) != null && StringUtils.isNotBlank(row.getCell(8).toString())) {
						role.setDescription(row.getCell(8).toString());
					}

					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						// 判断导入类型 1.覆盖 2.增量
						boolean t = true;
						if (attachmentBean.getType()==1) {
							role.setCreateTime(roleMap.get(row.getCell(0).toString()).getCreateTime());
							role.setUpdateTime(new Date());
							roleDao.updateByPrimaryKey(role);
							roleDepartmentExtDao.deleteRoleDepartmentListByExcel(roleDepartment);
							String success = str.toString() + "岗位编码(" + role.getRoleCode() + ")";
							successList.add(success);
							t = false;

						}

						if (t) {
							try {
								// 添加
								roleDao.insertSelective(role);
							} catch (Exception e) {
								throw new ResultFaultException("7_00003");
							}
						}

						if(roleDepartment.getRoleId()==null) {
							roleDepartment.setRoleId(role.getRoleId());
						}
						if(roleDepartment.getDepartmentId()!=null) {
							roleDepartmentDao.insert(roleDepartment);
						}
						
						
						if (row.getCell(1)!=null&& StringUtils.isNotBlank(row.getCell(1).toString())) {
							role.setRolePath(roleMap.get(row.getCell(1).toString()).getRolePath()  + role.getRoleId()+ "-");
						} else {
							role.setRolePath("-" + role.getRoleId() + "-");
						}
						roleDao.updateByPrimaryKeySelective(role);

						// 将ID更改为行数
						if (!t) {
							if (row.getCell(0).toString() != row.getCell(3).toString()) {
								roleMap.remove(row.getCell(0).toString());
								addRoleMap.remove(row.getCell(0).toString());
							}
						}
						addRoleMap.put(role.getRoleCode(), i + 1);
						roleMap.put(role.getRoleCode(), role);
					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("7_00003", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "岗位导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "岗位导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("7_00013");
	}
}
